package com.example.project.api.controller;

import cn.hutool.core.date.DateUtil;
import com.example.project.api.model.TbUser;
import com.example.project.api.model.TbWin;
import com.example.project.api.service.TbUserService;
import com.example.project.common.tools.R;
import com.example.project.common.tools.ResponseEnum;
import com.example.project.common.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * (user)表控制层
 *
 * @author ZhangHongRui
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class TbUserController {
    /**
     * 服务对象
     */
    @Autowired
    private TbUserService tbUserService;

    /**
     * 获取用户
     */
    @GetMapping("/getUser")
    public R getUser(HttpServletRequest request) {
        // 获取IP进行验证
        String ip = Utils.getIpAddr(request);
        TbUser tbUser = tbUserService.getUserByIp(ip);
        // 如果IP不存在为新用户
        if (ObjectUtils.isEmpty(tbUser)) {
            tbUser = new TbUser();
            tbUser.setUserIp(ip);
            tbUser.setUserNum(3);
            tbUser.setVisitsNum(1);
            tbUser.setLastVisitsTime(LocalDateTime.now());
            tbUserService.save(tbUser);
        } else {
            tbUser.setVisitsNum(tbUser.getVisitsNum() + 1);
            tbUser.setLastVisitsTime(LocalDateTime.now());
            tbUserService.updateById(tbUser);
        }
        log.info("ip:{} 访问了本网站,当前时间:{}", ip, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        return new R(ResponseEnum.SUCCESS, null);
    }

    /**
     * 返回用户ip
     */
    @GetMapping("/getIp")
    public R getWinByIp(HttpServletRequest request) {
        String ip = Utils.getIpAddr(request);
        return new R(ResponseEnum.SUCCESS, ip);
    }

}
